import { resources, assetManager, ImageAsset, SpriteFrame, Asset, Texture2D } from "cc";
import { ResCacheAsset } from "./ResCacheAsset";


export class ResCacheImage extends ResCacheAsset<Asset> {

    private _spriteFrame!: SpriteFrame | null;
    private _manualDestroy: boolean = false;


    protected onLoadRes() {

        this._manualDestroy = false;

        let url = this.path;

        if (url.startsWith("http:") || url.startsWith("https:")) {
            assetManager.loadRemote(url, (error, asset: ImageAsset) => {
                if (error) {
                    console.error(`加载远程图片失败：${this.path}`);
                    console.error(error);
                    this.loadFinish(null);
                    return;
                }
                this._spriteFrame = SpriteFrame.createWithImage(asset);
                this._manualDestroy = true;
                this.loadFinish(asset);
            });
        }
        else {
            if (url.endsWith("spriteFrame")) {
                resources.load(url, SpriteFrame, (error: any, asset: SpriteFrame) => {
                    if (error) {
                        console.error(`加载本地精灵图片失败：${this.path}`);
                        console.error(error);
                        this.loadFinish(null);
                        return;
                    }
                    this._spriteFrame = asset;
                    this.loadFinish(asset);
                });
            }
            else {
                resources.load(url, ImageAsset, (error: any, asset: ImageAsset) => {
                    if (error) {
                        console.error(`加载本地图片失败：${this.path}`);
                        console.error(error);
                        this.loadFinish(null);
                        return;
                    }
                    this._spriteFrame = SpriteFrame.createWithImage(asset);
                    // this._manualDestroy = true;
                    this.loadFinish(asset);
                });
            }
        }
    }

    public spawn(name?: string): any {
        this.ref++;
        this.tick = Date.now();
        return this._spriteFrame;
    }

    public unSpawn(obj?: any) {
        this.ref--;
        this.tick = Date.now();
    }

    public unSpawnAll(name: string) {
        this.ref = 0;
        this.tick = Date.now();
    }

    protected handleCallback(callback: Function, target: any) {
        let sf = this.spawn();
        callback.call(target, this, sf);
    }

    /**
     * 释放资源
     * @returns 
     */
    public release() {
        super.release();

        // if (this._manualDestroy && this._spriteFrame) {
        //     let texture = this._spriteFrame.texture;
        //     if (texture)
        //         texture.destroy();
        //     this._spriteFrame.destroy();
        //     this._spriteFrame = null;
        // }
    }
}